<template>
  <div class="users">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <hr>
    <el-row style="margin-top: 15px;" :gutter="20">
      <el-col :span="6">
        <el-input placeholder="请输入搜索关键字" class="input-with-select" v-model="query" autofocus @change="search">
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="success" plain @click="dialogVisible = true">添加用户</el-button>
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose">
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="姓名" prop="username">
              <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
              <el-input type="password" v-model="ruleForm.checkPassword" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item prop="mobile" label="手机号">
              <el-input v-model.number="ruleForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="add">确 定</el-button>
          </span>
        </el-dialog>
      </el-col>
    </el-row>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180">
      </el-table-column>
      <el-table-column prop="mobile" label="电话">
      </el-table-column>
      <el-table-column prop="status" label="用户状态">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.mg_state ? '已启用':'已禁用'" placement="top">
            <el-switch
              @change="changeState(scope.row)"
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="showEditDialog(scope.row)" plain type="primary">编辑</el-button>
          <el-dialog
            title="修改用户"
            :visible.sync="editVisible"
            width="40%">
            <el-form ref="editForm" :model="editForm" :rules="rules" status-icon label-width="100px">
              <el-form-item label="用户名">
                <el-tag type="info">{{ editForm.username }}</el-tag>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input placeholder="请输入邮箱" v-model="editForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="mobile">
                <el-input placeholder="请输入手机" v-model="editForm.mobile"></el-input>
              </el-form-item>
            </el-form>
            <template v-slot:footer>
              <span class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
              </span>
            </template>
          </el-dialog>
          <el-button type="danger" plain @click="del(scope.row)">删除</el-button>
          <el-button type="success" plain @click="getRoles(scope.row)">分配角色</el-button>
          <el-dialog title="分配角色" :visible.sync="roleVisible" width="40%">
            <el-form ref="roleForm" label-width="100px">
              <el-form-item label="用户名">
                <el-tag type="info">{{ scope.row.username }}</el-tag>
              </el-form-item>
              <el-form-item label="角色列表" prop="roles">
                <el-dropdown trigger="click" @command="handleCommand">
                  <el-button plain>
                    {{role_name}}<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="item.id" v-for="item in roles" :key="item.id">{{item.roleName}}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-form-item>
            </el-form>
            <template v-slot:footer>
              <span class="dialog-footer">
                <el-button @click="roleVisible = false">取 消</el-button>
                <el-button type="primary" @click="assignRole(scope.row)">确 定</el-button>
              </span>
            </template>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenum"
        :page-size="pagesize"
        :page-sizes="[10, 8, 6, 4, 2]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalPage">
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPassword !== '') {
          this.$refs.ruleForm.validateField('checkPassword')
        }
        callback()
      }
    }
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    let validateMobile = (rule, value, callback) => {
      console.log('------------', rule, value)
      let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (value === '') callback()
      if (!reg.test(value)) {
        callback(new Error('请输入正确手机号'))
      } else {
        callback()
      }
    }
    return {
      tableData: [],
      pagenum: 1,
      totalPage: null,
      pagesize: 2,
      query: '',
      dialogVisible: false,
      editVisible: false,
      roleVisible: false,
      formLabelWidth: '120px',
      editForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      roles: [],
      rid: null,
      role_name: '',
      ruleForm: {
        username: '',
        password: '',
        checkPassword: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '请输姓名', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, validator: validatePass, trigger: ['blur', 'change'] }
        ],
        checkPassword: [
          { required: true, validator: validatePass2, trigger: ['blur', 'change'] }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { type: 'number', validator: validateMobile, trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    changeState (row) {
      this.$axios({
        url: `users/${row.id}/state/${row.mg_state}`,
        method: 'put'
      }).then(res => {
        // console.log(res)
        const { msg, status } = res.meta
        if (status === 200) {
          this.$message.success('修改成功')
        } else {
          this.$message.error(msg)
        }
      })
    },
    handleSizeChange (val) {
      this.pagesize = val
      this.pagenum = 1
      this.getList()
    },
    handleCurrentChange (val) {
      this.pagenum = val
      this.getList()
    },
    search (value) {
      this.pagenum = 1
      this.getList()
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    close () {
      this.$refs['ruleForm'].resetFields()
      this.dialogVisible = false
    },
    add () {
      this.$refs['ruleForm'].validate(isPass => {
        console.log(isPass)
        if (isPass) {
          this.$axios({
            method: 'post',
            url: 'users',
            data: {
              username: this.ruleForm.username,
              password: this.ruleForm.password,
              email: this.ruleForm.email,
              mobile: this.ruleForm.mobile
            }
          }).then(res => {
            if (res.meta.status === 400) {
              this.$message.error(res.meta.msg)
              return
            }
            this.$message.success('添加成功')
            this.$refs['ruleForm'].resetFields()
            this.pagenum = Math.ceil((this.totalPage + 1) / this.pagesize)
            console.log(this.pagenum)
            this.getList()
          })
        } else {
          this.$message.success('添加失败')
          return false
        }
      })
      this.dialogVisible = false
    },
    del (row) {
      this.$confirm('确定要删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.pagenum = 1
        this.$axios({
          method: 'delete',
          url: `users/${row.id}`
        }).then(res => {
          // console.log(res)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.pagenum = Math.ceil((this.totalPage - 1) / this.pagesize)
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    showEditDialog ({ id, username, mobile, email }) {
      this.editVisible = true
      this.editForm.id = id
      this.editForm.username = username
      this.editForm.mobile = mobile
      this.editForm.email = email
    },
    editUser () {
      this.$refs.editForm.validate(isPass => {
        if (isPass) {
          const { id, email, mobile } = this.editForm
          this.$axios.put(`users/${id}`, { id, email, mobile }).then(res => {
            const { msg, status } = res.meta
            if (status === 200) {
              this.$message.success('更新成功')
              this.$refs.editForm.resetFields()
              this.getList()
            } else {
              this.$message.error(msg)
            }
          })
        } else {
          this.$message.error('更新失败')
        }
        this.editVisible = false
      })
    },
    getRoles (row) {
      this.roleVisible = true
      this.$axios.get('roles').then(res => {
        // console.log('roles', res)
        this.roles = res.data
      })
      this.role_name = this.tableData.find(item => item.id === row.id).role_name
    },
    handleCommand (command) {
      // console.log(command)
      this.rid = command
      this.$axios.get('roles/' + command).then(res => {
        // console.log(res)
        this.role_name = res.data.roleName
      })
    },
    assignRole (row) {
      this.$axios.put(`users/${row.id}/role`, { rid: this.rid }).then(res => {
        // console.log('assignRole', res)
        this.$message.success('修改角色成功')
        this.getList()
        this.roleVisible = false
      })
    },
    getList () {
      this.$axios({
        method: 'get',
        url: 'users',
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      }).then(res => {
        this.tableData = res.data.users
        this.totalPage = res.data.total
      })
    }
  },
  created () {
    this.getList()
  }
}
</script>

<style lang="scss" scoped>
  .el-breadcrumb{
    height: 30px;
    line-height: 30px;
  }
  .el-table{
    margin-top: 10px
  }
  .block{
    margin-top: 10px
  }
  .el-dropdown {
    vertical-align: top;
  }
  .el-dropdown + .el-dropdown {
    margin-left: 15px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
